﻿using System;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using FoodBank.Core.Models;

namespace FoodBank.Data
{
    public class FoodBankContext : DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<ProductCategory> Categories { get; set; }
        public DbSet<Brand> Brands { get; set; }
        public DbSet<UserProductConsumption> Consumptions { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<UserSetting> UserSettings { get; set; }

        public override int SaveChanges()
        {
            //TODO: get name of user 
            var auditUser = string.Empty;
            var auditDate = DateTime.UtcNow;

            foreach (DbEntityEntry<IAuditable> entry in ChangeTracker.Entries<IAuditable>())
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Entity.CreatedOn = auditDate;
                    entry.Entity.ModifiedOn = auditDate;
                    entry.Entity.CreatedBy = auditUser;
                    entry.Entity.ModifiedBy = auditUser;
                }
                else if (entry.State == EntityState.Modified)
                {
                    entry.Entity.ModifiedOn = auditDate;
                    entry.Entity.ModifiedBy = auditUser;
                }
            }

            return base.SaveChanges();
        }
    }
}